package com.yjj.springboot3.controller;


import com.yjj.springboot3.ai.service.AiService;
import com.yjj.springboot3.common.BaseResponse;
import com.yjj.springboot3.common.ErrorCode;
import com.yjj.springboot3.common.ResultUtils;
import com.yjj.springboot3.exception.ThrowUtils;
import com.yjj.springboot3.model.dto.conversation.ChatRequest;
import com.yjj.springboot3.model.dto.conversation.ConversationCreateRequest;
import com.yjj.springboot3.model.dto.conversation.ConversationDeleteRequest;
import com.yjj.springboot3.model.dto.conversation.ConversationQueryRequest;
import com.yjj.springboot3.model.entity.Conversation;
import com.yjj.springboot3.model.entity.User;
import com.yjj.springboot3.model.vo.ChatResponse;
import com.yjj.springboot3.model.vo.ConversationVO;
import com.yjj.springboot3.model.vo.ConversationListVO;
import com.yjj.springboot3.model.vo.MessageListVO;
import com.yjj.springboot3.model.vo.AdminConversationVO;
import com.yjj.springboot3.service.ConversationService;
import com.yjj.springboot3.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;



/**
 * 对话接口
 */
@RestController
@RequestMapping("/conversation")
@Slf4j

public class ConversationController {

    @Resource
    private ConversationService conversationService;

    @Autowired
    private UserService userService;

    @Resource
    private AiService aiService;

    /**
     * 创建对话
     */
    @PostMapping("/create")
    @Operation(summary = "创建对话", description = "创建一个新的对话")
    public BaseResponse<ConversationVO> createConversation(@RequestBody ConversationCreateRequest createRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(createRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        // 创建对话实体
        Conversation conversation = new Conversation();
        conversation.setStatus(0); // 待开始状态
        conversation.setUserId(loginUser.getId());

        // 设置标题，如果没有提供则使用默认标题
        String title = createRequest.getTitle();
        if (StringUtils.isBlank(title)) {
            title = "新对话";
        }
        // 注意：这里需要在Conversation实体中添加title字段，或者通过其他方式保存标题

        // 保存到数据库
        boolean result = conversationService.save(conversation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建对话失败");

        // 构建返回对象
        ConversationVO conversationVO = new ConversationVO();
        conversationVO.setConversationId(conversation.getId()); // 使用数据库主键id作为对话ID
        conversationVO.setTitle(title);
        conversationVO.setStatus(conversation.getStatus());
        conversationVO.setCreateTime(conversation.getCreateTime());

        log.info("创建对话成功，对话ID: {}", conversation.getId());
        return ResultUtils.success(conversationVO);
    }

    /**
     * AI聊天
     */
    @PostMapping("/chat")
    @Operation(summary = "AI聊天", description = "与AI进行对话交互")
    public BaseResponse<ChatResponse> chat(@RequestBody ChatRequest chatRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(chatRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(chatRequest.getConversationId() == null, ErrorCode.PARAMS_ERROR, "对话ID不能为空");
        ThrowUtils.throwIf(StringUtils.isBlank(chatRequest.getContent()), ErrorCode.PARAMS_ERROR, "消息内容不能为空");

        User loginUser = userService.getLoginUser(request);

        Long conversationId = chatRequest.getConversationId();
        String userInput = chatRequest.getContent();

        // 验证对话是否属于当前用户
        Conversation conversation = conversationService.getById(conversationId);
        ThrowUtils.throwIf(conversation == null, ErrorCode.NOT_FOUND_ERROR, "对话不存在");
        ThrowUtils.throwIf(!conversation.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权限访问此对话");

        try {
            // 调用AI服务获取回复
            String aiResponse=aiService.chat(conversationId, userInput);
            // 更新对话状态为进行中
            if (conversation.getStatus() == 0) {
                conversation.setStatus(1); // 对话中状态
                conversationService.updateById(conversation);
            }

            // 构建返回对象
            ChatResponse chatResponse = new ChatResponse();
            chatResponse.setConversationId(conversationId);
            chatResponse.setContent(aiResponse);
            chatResponse.setTimestamp(System.currentTimeMillis());

            log.info("AI聊天成功，对话ID: {}, 回复长度: {}", conversationId, aiResponse.length());
            return ResultUtils.success(chatResponse);

        } catch (Exception e) {
            log.error("AI聊天失败，对话ID: {}, 错误: {}", conversationId, e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "AI聊天失败: " + e.getMessage());
        }
    }

    /**
     * 删除对话
     */
    @PostMapping("/delete")
    @Operation(summary = "删除对话", description = "删除指定的对话")
    public BaseResponse<Boolean> deleteConversation(@RequestBody ConversationDeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(deleteRequest.getConversationId() == null, ErrorCode.PARAMS_ERROR, "对话ID不能为空");

        User loginUser = userService.getLoginUser(request);
        Long conversationId = deleteRequest.getConversationId();

        boolean result = conversationService.deleteUserConversation(conversationId, loginUser.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除对话失败");

        log.info("删除对话成功，对话ID: {}, 用户ID: {}", conversationId, loginUser.getId());
        return ResultUtils.success(true);
    }

    /**
     * 获取我的对话列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取我的对话列表", description = "获取当前用户的对话列表")
    public BaseResponse<List<ConversationListVO>> getMyConversationList(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long pageSize,
            HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        List<ConversationListVO> conversationList = conversationService.getUserConversationList(
                loginUser.getId(), current, pageSize);

        log.info("获取用户对话列表成功，用户ID: {}, 对话数量: {}", loginUser.getId(), conversationList.size());
        return ResultUtils.success(conversationList);
    }

    /**
     * 根据对话ID获取消息列表
     */
    @GetMapping("/messages/{conversationId}")
    @Operation(summary = "获取消息列表", description = "根据对话ID获取消息列表")
    public BaseResponse<MessageListVO> getMessageList(@PathVariable Long conversationId, HttpServletRequest request) {
        ThrowUtils.throwIf(conversationId == null, ErrorCode.PARAMS_ERROR, "对话ID不能为空");

        User loginUser = userService.getLoginUser(request);
        MessageListVO messageList = conversationService.getMessageList(conversationId, loginUser.getId());
        ThrowUtils.throwIf(messageList == null, ErrorCode.NOT_FOUND_ERROR, "对话不存在或无权限访问");

        log.info("获取消息列表成功，对话ID: {}, 消息数量: {}", conversationId, messageList.getTotalCount());
        return ResultUtils.success(messageList);
    }

    // ======================== 管理员功能 ========================

    /**
     * 管理员获取对话列表（分页）
     */
    @GetMapping("/admin/list")
    @Operation(summary = "管理员获取对话列表", description = "管理员获取所有对话列表（分页）")
    public BaseResponse<Page<AdminConversationVO>> getAdminConversationList(ConversationQueryRequest queryRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(!userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "无管理员权限");

        Page<AdminConversationVO> conversationPage = conversationService.getAdminConversationPage(queryRequest);

        log.info("管理员获取对话列表成功，页码: {}, 页面大小: {}, 总数: {}",
                queryRequest.getCurrent(), queryRequest.getPageSize(), conversationPage.getTotal());
        return ResultUtils.success(conversationPage);
    }

    /**
     * 管理员删除对话
     */
    @PostMapping("/admin/delete")
    @Operation(summary = "管理员删除对话", description = "管理员删除指定对话")
    public BaseResponse<Boolean> adminDeleteConversation(@RequestBody ConversationDeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(deleteRequest.getConversationId() == null, ErrorCode.PARAMS_ERROR, "对话ID不能为空");

        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(!userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "无管理员权限");

        Long conversationId = deleteRequest.getConversationId();
        boolean result = conversationService.adminDeleteConversation(conversationId);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除对话失败");

        log.info("管理员删除对话成功，对话ID: {}, 操作员: {}", conversationId, loginUser.getUserAccount());
        return ResultUtils.success(true);
    }

    /**
     * 管理员获取对话详情（包含完整消息）
     */
    @GetMapping("/admin/detail/{conversationId}")
    @Operation(summary = "管理员获取对话详情", description = "管理员获取指定对话的详细信息")
    public BaseResponse<MessageListVO> getAdminConversationDetail(@PathVariable Long conversationId, HttpServletRequest request) {
        ThrowUtils.throwIf(conversationId == null, ErrorCode.PARAMS_ERROR, "对话ID不能为空");

        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(!userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "无管理员权限");

        MessageListVO conversationDetail = conversationService.getAdminConversationDetail(conversationId);
        ThrowUtils.throwIf(conversationDetail == null, ErrorCode.NOT_FOUND_ERROR, "对话不存在");

        log.info("管理员获取对话详情成功，对话ID: {}, 消息数量: {}", conversationId, conversationDetail.getTotalCount());
        return ResultUtils.success(conversationDetail);
    }
}
